package com.cdgeekcamp.redas.recr_page_worker.component;

import com.cdgeekcamp.redas.db.model.RecrPageState;
import com.cdgeekcamp.redas.db.model.RecrPageStateRepository;
import com.cdgeekcamp.redas.lib.core.RecrPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

@Component
public class RecrPageStateBuildServiceImpl implements RecrPageBuildService {
    @Autowired
    private RecrPageStateRepository recrPageStates;

    public Integer build(RecrPage recrPage, Integer... relatedIds) {
        Integer recrPageStorageId = relatedIds[0];
        Integer positionId = relatedIds[1];

        // 只能通过职位编号检查以前是否入库，避免重复入库
        // 因为同公司同职位是不会入库两次的，只会一次
        Optional<RecrPageState> recrPageStateOpt = recrPageStates.findByPositionId(positionId);
        RecrPageState recrPageState;

        if (recrPageStateOpt.isEmpty()) {
            recrPageState = recrPageStates.save(new RecrPageState(recrPageStorageId, positionId, new Date()));
            log.info(String.format("职位编号：%s 不存在状态标记，新建中......", positionId));
        } else {
            recrPageState = recrPageStateOpt.get();
            recrPageState.setMarkDateTime(new Date());
            recrPageStates.save(recrPageState);

            log.info(String.format("职位编号：%s 已经存在状态标记，更新中......", positionId));
        }

        return recrPageState.getId();
    }
}
